<?php
/**
 * 育儿周刊发送程序。
 */
if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

require './source/function/function_date.php';
require './source/function/function_send_weekly.php';
require './source/function/function_mail.php';

$lockfile = DISCUZ_ROOT.'./data/send_babyarticle.lock';
@$filemtime = filemtime($lockfile);

if($_G['timestamp'] - $filemtime < 5) {
	exit();
}
touch($lockfile);

$current_monday = dweek('',  1);
$last_email_send = strtotime($current_monday);

$sql = "select id, email, 41 - ceiling((birth_days - $last_email_send) / (7 * 86400) )  as week_no, last_email_send, update_time 
        from ".DB::table('article_subscribe')." where prepare_pregnancy = 0 and unsubscribe = 0 and email_confirmed = 1 
        and ( last_email_send is null or last_email_send < $last_email_send ) limit 5120";

$BATCH_SIZE = 32; // 每发送$BATCH_SIZE封电子邮件,标记一次当前时间
$i = 0;

$success = array();
$article_map = array();
$unsubscribe_url = 'know.php?mod=unsubscribe&id=';
$query = DB::query($sql);
while ($row = DB::fetch($query)) {
	if ($i == $BATCH_SIZE){
		touch($lockfile);
		update_last_email_send($success);

		$success = array();
		$i = 0;
	}

	$id = $row['id'];
	$to = $row['email'];
	$week_no = $row['week_no'];
	$ut = $row['update_time'];

	if (!empty($article_map[$week_no]) && is_array($article_map[$week_no])){
		list($subject, $message) = $article_map[$week_no];
	}
	else {
		list($subject, $message) = $article_map[$week_no] = read_article($week_no);
	}
	
	if (empty($subject) || empty($message)) {
		continue;
	}
	
	$message = str_replace('#unsubscribe_url#', $unsubscribe_url.$id.'&ut='.$ut, $message);
	if(!sendmail($to, $subject, $message)) {
		runlog('sendmail', "向 $to [$id]发送 $subject 失败.");
	} else {
		$success[] = array('data' => array('last_email_send' => $last_email_send), 'condition' => array('id' => $row['id']));
	}

	++$i;
}

update_last_email_send($success);

function update_last_email_send ($success = array()) {
	foreach ($success as $tmp) {
		DB::update('article_subscribe', $tmp['data'], $tmp['condition']);
	}
}

?>